package com.leadnews.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.ServiceException;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传工具类
 */
@Data
@Component
@ConfigurationProperties(prefix = "spring.oss")
@Slf4j
public class OssUtil {

    private String host;
 
    private String bucketName;
 
    private String endpoint;
 
    private String accessKeyId;
 
    private String accessKeySecret;
 
    /**
     * 上传文件
     * @param file
     * @return
     */

    public String upload(InputStream inputStream,String s) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 上传文件流。
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM-dd");//创建一个日期格式.
        String format1 = format.format(date);
        String filename="material/"+format1+"/"+UUID.randomUUID()+"."+s;

            ossClient.putObject(bucketName, filename, inputStream);
            log.info("oss上传成功：{}",host+filename);

        // 关闭OSSClient。
        ossClient.shutdown();
    return  host+filename;
    }
 
    /**
     * 删除文件
     * @param url
     */
    public void remove(String url) {
         url = url.substring(43);
        // 创建OSSClient实例。
        log.info("oss 素材路径：{}",url);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        boolean exist = ossClient.doesObjectExist(bucketName, url);
        // 删除操作
        if (exist) {
            ossClient.deleteObject(bucketName, url);
        }
        // 关闭OSSClient。
        ossClient.shutdown();
    }
 
    /**
     * 校验文件
     * @param len
     * @param size
     * @param unit
     * @return
     */

 
}